package com.dp;

public class Solution44 {
    public int longestCommonSubsequence(String text1, String text2) {
        int[][] dp = new int[text1.length()][text2.length()];
        int flag = 0;
        for (int i = 0; i < text2.length(); i++) {
            if (text1.charAt(0) == text2.charAt(i)) {
                flag = 1;
            }
            if (flag == 1) dp[0][i] = 1;
        }
        flag = 0;
        for (int i = 0; i < text1.length(); i++) {
            if (text2.charAt(0) == text1.charAt(i)) {
                flag = 1;
            }
            if (flag == 1) dp[i][0] = 1;
        }
        for (int i = 1; i < text1.length(); i++) {
            char c1 = text1.charAt(i);
            for (int j = 1; j < text2.length(); j++) {
                char c2 = text2.charAt(j);
                if (c1 == c2) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }
        return dp[text1.length() - 1][text2.length() - 1];
    }
}
